package com.example.demo.converter;

import com.example.demo.model.PersonalInfo;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component
public class PersonalInfoConverter implements Converter<Object, Object> {

    @Override
    public Object convert(Object source) {
        if (source instanceof PersonalInfo personalInfo) {
            // 获取当前用户的角色
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (principal instanceof UserDetails) {
                UserDetails userDetails = (UserDetails) principal;
                Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
                if (!isUserAdmin(authorities)) {
                    // 如果不是管理员角色，进行掩码处理
                    String password = personalInfo.getPassword();
                    if (password != null) {
                        personalInfo.setPassword(maskPassword(password));
                    }
                    String phoneNumber = personalInfo.getPhoneNumber();
                    if (phoneNumber != null && phoneNumber.length() == 11) {
                        personalInfo.setPhoneNumber(maskPhoneNumber(phoneNumber));
                    }
                }
            } else {
                // 如果没有登录用户，进行掩码处理
                String password = personalInfo.getPassword();
                if (password != null) {
                    personalInfo.setPassword(maskPassword(password));
                }
                String phoneNumber = personalInfo.getPhoneNumber();
                if (phoneNumber != null && phoneNumber.length() == 11) {
                    personalInfo.setPhoneNumber(maskPhoneNumber(phoneNumber));
                }
            }
            return personalInfo;
        }
        return source;
    }

    private boolean isUserAdmin(Collection<? extends GrantedAuthority> authorities) {
        for (GrantedAuthority authority : authorities) {
            if (authority.getAuthority().equals("ROLE_ADMIN")) {
                return true;
            }
        }
        return false;
    }

    private String maskPassword(String password) {
        return "******";
        // return "*".repeat(password.length());
    }

    private String maskPhoneNumber(String phoneNumber) {
        return phoneNumber.substring(0, 3) + "*".repeat(phoneNumber.length() - 7) + phoneNumber.substring(phoneNumber.length() - 4);
    }
}